import { getUserInfoByUserDDId } from "@/api/login";
import { selectPmLogByPmId } from "@/api/log"
import { ref, nextTick, watch } from "vue";

function useLog() {

  let logDataList = ref<PmLog.LogData[]>([])
  function setLogDatList(data: PmLog.LogData[]) {
    nextTick(() => {
      logDataList.value = data
    })
  }
  function updateLogDataList({ pmId, isGetAllUserInfo = false }: { pmId: number, isGetAllUserInfo?: boolean }) {
    selectPmLogByPmId({ pmId }).then(async res => {
      res.data.sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime())
      setLogDatList(res.data)

      /**去重日志中的用户Id，并获取用户信息 */
      if (isGetAllUserInfo) {
        getAllUserInfo(res.data)
      }

    }).catch(err => { })
  }

  function getLogDataList({ pmId, isGetAllUserInfo = false, isUpdateLogDataList = false, success, fail }: { pmId: number, isGetAllUserInfo?: boolean, isUpdateLogDataList?: boolean, success?: (data: PmLog.LogData[]) => void, fail?: () => void }) {
    selectPmLogByPmId({ pmId }).then(async res => {

      res.data.sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime())
      if (isUpdateLogDataList) {
        setLogDatList(res.data)
      }

      /**去重日志中的用户Id，并获取用户信息 */
      if (isGetAllUserInfo) {
        getAllUserInfo(res.data)
      }

      success && success(res.data)
    }).catch(err => {
      fail && fail()
    })
  }

  async function getAllUserInfo(data: PmLog.LogData[]) {
    const userList = Array.from(new Set(data.map(item => item.makeUserDDId)))
    for (let i = 0; i < userList.length; i++) {
      let userDDId = userList[i]
      let userInfoRes = await getUserInfoByUserDDId({ userDDId })
      if (userInfoRes && userInfoRes.data) {
        for (let i = 0; i < logDataList.value.length; i++) {
          if (logDataList.value[i].makeUserDDId === userInfoRes.data.userId) {
            logDataList.value[i].avatar = userInfoRes.data.avatar
          }
        }
      }
    }
  }




  watch(() => logDataList.value, n => {
  }, { immediate: true })

  return {
    logDataList,
    updateLogDataList,
    getLogDataList
  }
}

export default useLog